package com.ddch.testmessager;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private static final String TAG = "liaoming";
    private GetRelyHandler mGetRelyHandler = new GetRelyHandler();
    private Messenger mReplyMessenger = new Messenger(mGetRelyHandler);
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewById(R.id.bindService).setOnClickListener(this);
        findViewById(R.id.unBindService).setOnClickListener(this);
        Intent intent = new Intent(this, MessagerService.class);
        startService(intent);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.bindService:
                Intent intent = new Intent(this, MessagerService.class);
                // 绑定服务
                startService(intent);
                bindService(intent, mConnection, BIND_AUTO_CREATE);
                break;
            case R.id.unBindService:
                unbindService(mConnection);
                break;
            default:
                break;

        }
    }
    private ServiceConnection mConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            // 获取服务端关联的Messenger对象
            Messenger mService = new Messenger(service);
            // 创建Message对象
            Message message = Message.obtain();
            Bundle bundle = new Bundle();
            bundle.putString("client", "今天出去玩吗");
            message.setData(bundle);
            // 在message中添加一个回复mReplyMessenger对象
            message.replyTo = mReplyMessenger;
            try {
                mService.send(message);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.d(TAG, "onServiceDisconnected");
        }
    };
    public static class GetRelyHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Bundle bundle = msg.getData();
            String serviceMsg = bundle.getString("service");
            Log.d(TAG, "来自服务端的回复：" + serviceMsg);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(mConnection);
        Log.d(TAG, "onDestroy");
    }

}
